package org.taobao.ibatiside.ui.util;

import java.io.IOException;
import java.util.Iterator;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMap.Entry;
import org.taobao.ibatiside.model.mapperv2.DocumentRoot;
import org.taobao.ibatiside.model.mapperv2.GeneralStatement;
import org.taobao.ibatiside.model.mapperv2.Mapperv2Factory;
import org.taobao.ibatiside.model.mapperv2.Mapperv2Package;
import org.taobao.ibatiside.model.mapperv2.SqlMap;
import org.taobao.ibatiside.model.mapperv2.util.Mapperv2XMLProcessor;

public class Mapper2XMLProcessor extends Mapperv2XMLProcessor {
	public boolean save2File(SqlMap mapper, IPath file){
		Resource resource = createResourceSet().createResource(URI.createPlatformResourceURI(file.toString(),false));
		DocumentRoot root = Mapperv2Factory.eINSTANCE.createDocumentRoot();
		root.setSqlMap(mapper);
		resource.getContents().add(root);
		try {
			resource.save(null);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	public void removeStmt(IFile mapperFile, String stmtId){
		if (StringUtils.isBlank(stmtId)) return;
		Resource resource = createResourceSet().getResource(URI.createPlatformResourceURI(mapperFile.getFullPath().toString(),false),true);
		DocumentRoot root = (DocumentRoot) resource.getContents().get(0);
		FeatureMap data_map = root.getSqlMap().getGroup();
		for (Iterator<FeatureMap.Entry> entries = data_map.iterator(); entries.hasNext();){
			Entry one_entry = entries.next();
			int feature_id = one_entry.getEStructuralFeature().getFeatureID();
			if (feature_id == Mapperv2Package.SQL_MAP__SELECT || feature_id == Mapperv2Package.SQL_MAP__INSERT
					|| feature_id == Mapperv2Package.SQL_MAP__DELETE || feature_id == Mapperv2Package.SQL_MAP__UPDATE
					|| feature_id == Mapperv2Package.SQL_MAP__STATEMENT || feature_id == Mapperv2Package.SQL_MAP__PROCEDURE){
				GeneralStatement statement = (GeneralStatement) one_entry.getValue();
				if (stmtId.equals(statement.getId())){
					entries.remove();
				}
			}
		}
		try {
			resource.save(null);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
